﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Consul;

namespace MicroContainers.AspCore.Consul.ServiceDiscovery
{
    public class ServiceDiscovery : IServiceDiscovery
    {
        private readonly List<ConsulService> ConsulServices = new List<ConsulService>();

        private readonly IConsulClient _consulClient;

        private readonly ServiceDiscoveryConfig _config;

        public ServiceDiscovery(IConsulClient cousulClient)
        {
            _consulClient = cousulClient;
            _config = new ServiceDiscoveryConfig();
        }

        public async void Config(Action<ServiceDiscoveryConfig> configAction)
        {
            configAction(_config);
            ConsulServices.Clear();

            foreach (var serviceIdentity in _config.Services)
            {
                ConsulServices.Add(new ConsulService { Identity = serviceIdentity });
            }

            await InitServices();
        }

        private async Task InitServices()
        {
            var services = await _consulClient.Agent.Services();

            foreach (var consulService in ConsulServices)
            {
                consulService.Init(services.Response);
            }
        }

        public string Get(string name)
        {
            var service = ConsulServices.FirstOrDefault(x => x.Identity.Name == name);
            return service?.Get();
        }

        public string GetNext(string name)
        {
            var service = ConsulServices.FirstOrDefault(x => x.Identity.Name == name);
            return service?.GetNext();
        }
    }
}
